package com.oro.dao.impl;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oro.dao.UserDao;
import com.oro.domain.Authority;
import com.oro.domain.User;

public class HibernateUserDaoSupport extends HibernateDaoSupport implements
		UserDao {
	
	

	
	Logger logger;

	
	@Override
	public void deleteAuthorities() {
		getHibernateTemplate().deleteAll(getAuthorities());
	}

	@Override
	public void deleteAuthority(Long id) {
		getHibernateTemplate().delete(getAuthority(id));

	}

	
	@Override
	public void deleteAuthority(String role) {
		getHibernateTemplate().deleteAll(
				getHibernateTemplate().find("from Authority where role = ?", role));

	}

	
	@Override
	public void deleteUser(Long id) {
		getHibernateTemplate().delete(getUser(id));

	}

	
	@Override
	public void deleteUsers() {
		getHibernateTemplate().deleteAll(getUsers());

	}

	
	@Override
	@SuppressWarnings("unchecked")
	
	public List<Authority> getAuthorities() {
		return getHibernateTemplate().find("from Authority");
	}

	
	@Override
	public Authority getAuthority(Long id) {
		return getHibernateTemplate().get(Authority.class, id);
	}

	
	@Override
	public Authority getAuthority(String role) {
		@SuppressWarnings("unchecked")
		List<Authority> res = getHibernateTemplate().find(
				"from Authority au where au.role = ?", role);
		if (res.isEmpty())
			return null;
		else
			return res.get(0);
	}

	
	private Logger getLogger() {
		if (logger == null) {
			logger = Logger.getLogger(HibernateUserDaoSupport.class);
		}
		return logger;
	}

	
	@Override
	public User getUser(Long id) {
		return getHibernateTemplate().get(User.class, id);
	}

	
	@Override
	public User getUserByUsername(String username) {
		@SuppressWarnings("unchecked")
		List<User> res = getHibernateTemplate().find(
				"from User u where u.username = ?", username);
		if (res.isEmpty())
			return null;
		else
			return res.get(0);

	}

	@Override
	@SuppressWarnings("unchecked")
	
	public List<User> getUsers() {
		return getHibernateTemplate().find("from User");
	}
	
	@PostConstruct
	public void postConstruct() {
		getLogger().info("HibernateUserDaoSupport has been constructed.");
	}
	
	@PreDestroy
	public void preDestroy() {
		getLogger().info("HibernateUserDaoSupport is being destroyed.");
	}

	@Override
	public void save(Authority au) {
		getHibernateTemplate().saveOrUpdate(au);

	}
	
	@Override
	public void save(List<Authority> authorities) {
		getHibernateTemplate().saveOrUpdateAll(authorities);
		
	}

	
	@Override
	public void save(User user) {
		getHibernateTemplate().saveOrUpdate(user);

	}

}
